package com.wangzh.king.helper;

import com.wangzh.king.ConfigConstant;
import com.wangzh.king.annotation.Controller;
import com.wangzh.king.annotation.Service;
import com.wangzh.king.utils.ClassUtils;
import com.wangzh.king.utils.PropUtils;
import com.wangzh.king.utils.ReflectionUtils;

import java.util.*;

/**
 * 获取标注业务注解的bean
 * User: wangzh
 * Date: 2016/8/25
 * Time: 13:58
 */
public class BeanHelper {
    //存放bean
    private static Map<Class<?>,Object> beanMap = new HashMap<Class<?>,Object>();
    private static Set<Class<?>> classSet = new HashSet<Class<?>>();

    static {
        Properties properties = PropUtils.getProp("/king.properties");
        //TODO 有一些问题
        classSet = ClassUtils.getClassByPackageName(PropUtils.getValue(properties, ConfigConstant.BASE_PACKAGE));
    }

    /**
     * 获得标注@Controller的bean
      * @return
     */
    public static Map<Class<?>,Object> getControllerMap(){
        Map<Class<?>,Object> controllerMap = new HashMap<Class<?>,Object>();
        for(Class<?> cls : classSet){
            if(cls.isAnnotationPresent(Controller.class)){
                controllerMap.put(cls, ReflectionUtils.newObj(cls));
            }
        }
        return controllerMap;
    }

    /**
     * 获得标注@Service的bean
     * @return
     */
    public static Map<Class<?>,Object> getServiceMap(){
        Map<Class<?>,Object> serviceMap = new HashMap<Class<?>,Object>();
        for(Class<?> cls : classSet){
            if(cls.isAnnotationPresent(Service.class)){
                serviceMap.put(cls, ReflectionUtils.newObj(cls));
            }
        }
        return serviceMap;
    }


    /**
     * 获得标注@Controller @Service的bean
     * @return
     */
    public static Map<Class<?>,Object> getBeanMap(){
        beanMap.putAll(getControllerMap());
        beanMap.putAll(getServiceMap());
        return beanMap;
    }

    /**
     * 根据Class获得bean对象
     * @param cls
     * @param <T>
     * @return
     */
    public static <T>T getBean(Class<T> cls){
        //TODO 空判断
        return (T) beanMap.get(cls);
    }



}
